package com.itmk.web.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itmk.utils.ResultUtils;
import com.itmk.utils.ResultVo;
import com.itmk.web.goods.entity.Goods;
import com.itmk.web.goods.service.GoodsService;
import com.itmk.web.order.entity.Order;
import com.itmk.web.order.entity.OrderListParm;
import com.itmk.web.order.entity.OrderVo;
import com.itmk.web.order.mapper.OrderMapper;
import com.itmk.web.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private GoodsService goodsService;

    @Override
    @Transactional
    public void createOrder(Order order) {
//        如果商品已下架，status为0,则无法生成订单
        Goods goods = goodsService.getById(order.getGoodsId());
        if (goods.getStatus() == 0) {
            System.out.println("商品已下架");

        } else {
            //        插入订单数据
            order.setCreatedAt(new Date());
            int insert = this.baseMapper.insert(order);
//  如果订单插入成功(影响行数>0) 更新商品状态
            if (insert > 0) {
                UpdateWrapper<Goods> queryWrapper = new UpdateWrapper<>();
                queryWrapper.lambda().set(Goods::getStatus, 0)
                        .eq(Goods::getGoodsId, order.getGoodsId());
                goodsService.update(queryWrapper);

            }

        }
    }

    @Override
    public IPage<OrderVo> getList(OrderListParm parm) {
        IPage<OrderVo> page =new Page<>(parm.getCurrentPage(),parm.getPageSize());
        return this.baseMapper.getList(page,parm.getGoodsName());
    }


    @Override
    public List<Map<String, Object>> getOrderCountLast7Days() {
        LocalDate now = LocalDate.now();
        LocalDate startDate = now.minusDays(6);

        return baseMapper.selectOrderCountByDate(startDate, now);
    }
}
